package com.by.heartbeats.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.by.heartbeats.nacos.HeartbeatsConfig;
import com.by.mqsender.support.ByMqSupport;
import com.by.toolkit.consts.GlobalConst;
import com.by.toolkit.consts.MqTagConst;
import com.by.toolkit.model.Resp;
import com.by.toolkit.platform.ByContext;
import com.google.common.collect.ImmutableMap;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Tag(name = "心跳上报")
@Slf4j
@RestController
@RequestMapping("/heartbeat")
public class HeartbeatsController {

    private static final Logger HEARTBEAT = LoggerFactory.getLogger("businesslog");

    private static final JSONPath CONTENT_JSON_PATH = JSONPath.of("$.eventData.channel");

    @Resource
    private ByMqSupport byMqSupport;

    @Resource
    private HeartbeatsConfig heartbeatsConfig;

    @Operation(summary = "上报")
    @PostMapping("/record")
    public Resp<Void> record(@RequestBody JSONObject info) {
        // 增加请求id
        info.put("byExtraData", ByContext.getAll());
        // 增加服务器接收时间
        info.put("serverTime", System.currentTimeMillis());
        HEARTBEAT.info(info.toJSONString());

        String eventName = info.getString(GlobalConst.EVENT_NAME);
        List<String> supportEventNames = Optional.ofNullable(heartbeatsConfig.getSupportEventNames()).orElse(Collections.emptyList());
        if (supportEventNames.contains(eventName)) {
            byMqSupport.sendAsync(info, MqTagConst.HEARTBEAT);
        }

        String channelNo = (String) info.eval(CONTENT_JSON_PATH);
        if (StringUtils.isNotBlank(channelNo)) {
            byMqSupport.sendAsync(
                    ImmutableMap.of(
                            "channelNo", channelNo,
                            "channelStatisticDateTime", LocalDateTime.now()),
                    MqTagConst.CHANNEL_STATISTIC_MSG);
        }
        return Resp.ok();
    }

}
